package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class AutoSupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    /**
     * 实现自动补货工单
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {

        SupplyContract contract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        String innerCode = contract.getInnerCode();
        //根据设备编号查询到对应售货机信息
        VmVO vmInfo = vmService.getVMInfo(innerCode);

        List<SupplyChannel> supplyData = contract.getSupplyData();
        TaskViewModel model = new TaskViewModel();

        model.setCreateType(0);
        model.setInnerCode(innerCode);
        Integer userIdFromRedis = taskService.getSupplyId(vmInfo);
        model.setUserId(userIdFromRedis);
        model.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        model.setDesc("自动补货工单");
        //设置补货详情
        List<TaskDetailsViewModel> collect = supplyData.stream().map(new Function<SupplyChannel, TaskDetailsViewModel>() {
            @Override
            public TaskDetailsViewModel apply(SupplyChannel supplyChannel) {
                TaskDetailsViewModel td = new TaskDetailsViewModel();
                td.setChannelCode(supplyChannel.getChannelId());
                td.setExpectCapacity(supplyChannel.getCapacity());
                td.setSkuId(supplyChannel.getSkuId());
                td.setSkuImage(supplyChannel.getSkuImage());
                td.setSkuName(supplyChannel.getSkuName());
                return td;
            }
        }).collect(Collectors.toList());
        model.setDetails(collect);
        taskService.createTask(model);
    }
}
